<?php include_once 'header.php'; ?>
<style>
    .product-delete:hover{color:red;}
</style>
<aside class="right-side">
    <section class="content-header">
        <h1>
            Inventory
            <small>Stock Management</small>
        </h1>
        <ol class="breadcrumb">
            <li><a href="#"><i class="fa fa-cubes"></i> Inventory</a></li>
            <li class="active">Stock</li>
        </ol>
    </section>
    <section class="content">
        <div class="row">
            <div class="col-md-12">
                <div class="box box-info">
                    <div class="box-header">
                        <div class="col-md-4">
                            <h3 class="box-title"><i class="fa fa-cubes"></i> Products</h3>
                        </div>
                        <div class="col-md-4" style="padding:0;">
                            <div class="input-group margin">
                                <input id="filter-product-name" class="form-control" type="text"
                                       placeholder="Search Product By Name">
                                    <span class="input-group-btn">
                                        <button id="filter-search" class="btn btn-info btn-flat ladda-button"
                                                data-style="slide-right" type="button">Go
                                        </button>
                                    </span>
                            </div>
                        </div>
                        <div class="col-md-2" style="padding:0;">
                            <div class="form-group margin">
                                <select class="form-control" name="filter-category" id="filter-category"
                                        style="font-size:12px;">
                                    <option value="-1">All</option>
                                    <?php
                                    foreach ($categories as $category) {
                                        if ($category->getParent() == null) {
                                            echo "<option value='' style='color:#999999;'> ---" . $category->getName() . " --- </option>";
                                            foreach ($categories as $sub) {
                                                if ($sub->getParent() != null && $sub->getParent()->getId() == $category->getId()) {
                                                    echo "<option value='" . $sub->getId() . "'>" . $sub->getName() . "</option>";
                                                }
                                            }
                                        }
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2" style="text-align:right;padding-top:10px;">

                            <button class="btn btn-warning" data-toggle="modal" data-target="#myModal"><i
                                    class="fa fa-plus-square"></i> &nbsp;Add New Product
                            </button>
                        </div>
                    </div>
                    <div class="box-body" style="min-height:600px;">
                        <div id="product-grid" class="row">
                        </div>
                        <div id="display-product-template" class="col-md-3" style="display:none;">
                            <div class="box box-solid">
                                <div class="box-header">
                                    <h3 class="box-title" style="width:100%;"><span class="display-product-name">Product Name</span>
                                        <small class="display-product-category">Category</small>
                                        <small class="product-delete" style="font-size:18px;cursor: pointer;float: right; margin-right: 5px;"><i class="fa fa-trash-o"></i></small>
                                    </h3>
                                </div>
                                <div class="box-body">
                                    <form class="product-stock-form">
                                        <input type="hidden" name="p-id"/>
                                        <img class="p-image" alt="Failed to load Product Image." style="width:100%;"
                                             data-bttrlazyloading-sm-width="226"
                                             data-bttrlazyloading-sm-height="170"
                                             data-bttrlazyloading-md-width="226"
                                             data-bttrlazyloading-md-height="170"
                                             data-bttrlazyloading-lg-width="226"
                                             data-bttrlazyloading-lg-height="170">

                                        <div class="row" style="padding-top:10px;">
                                            <div class="col-md-12">
                                                <div class="col-md-8" style="padding:0;">
                                                    <div class="form-group">
                                                        <select class="form-control location-drop" name="p-location"
                                                                style="font-size:12px;">
                                                            <option value="-1" style="color:#999999;"> Select Location
                                                            </option>
                                                            <?php
                                                            foreach ($locations as $location) {
                                                                echo "<option value='" . $location->getId() . "'>" . $location->getName() . "</option>";
                                                            }
                                                            ?>
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="col-md-4" style="padding:0;text-align: right;">
                                                    <button type='button'
                                                            class='btn btn-default table-action-button ladda-button edit-product'
                                                            data-style='slide-right' style="height:34px;">
                                                        <i class='fa fa-pencil'></i>
                                                    </button>
                                                </div>
                                            </div>
                                            <div class="col-md-12">
                                                <div class="col-md-12" style="padding:0;">
                                                    <table class="table table-bordered">
                                                        <tr>
                                                            <td></td>
                                                            <td>Actual</td>
                                                            <td>Total</td>
                                                        </tr>
                                                        <tr>
                                                            <td>Product</td>
                                                            <td><span class="product-actual-stock"> 0</span></td>
                                                            <td><span class="product-total-stock"> 0</span></td>
                                                        </tr>
                                                        <tr>
                                                            <td>Overall</td>
                                                            <td><span class="grand-total-actual-stock"> 0</span></td>
                                                            <td><span class="grand-total-stock"> 0</span></td>
                                                        </tr>
                                                    </table>
                                                </div>
                                                <div class="col-md-6" style="padding-left:0;margin-top:5px;">
                                                    <div class="form-group">
                                                        <label for="product-name">Price per 100</label>
                                                        <input type="text" class="form-control number-input"
                                                               name="p-price">
                                                    </div>
                                                </div>
                                                <div class="col-md-6" style="padding-right:0;margin-top:5px;">
                                                    <div class="form-group">
                                                        <label for="product-name">Discount</label>
                                                        <input type="text" class="form-control number-input"
                                                               name="p-discount">
                                                    </div>
                                                </div>
                                                <div class="col-md-8" style="padding:0;">
                                                    <div class="form-group">
                                                        <label for="product-name">New Stock</label>
                                                        <input type="text" class="form-control number-input"
                                                               name="p-new-stock"
                                                               value="0">
                                                    </div>
                                                </div>
                                                <div class="col-md-4" style="padding:0;text-align: right;">
                                                    <button type="submit"
                                                            class="btn btn-primary ladda-button product-stock-form-button"
                                                            data-style="slide-right" style="margin-top:25px"/>
                                                    Save
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                                <div class="overlay" style="display:none"></div>
                                <div class="loading-img" style="display: none"></div>
                            </div>
                        </div>
                    </div>
                    <div class="overlay product-grid-loader"></div>
                    <div class="loading-img product-grid-loader"></div>
                </div>
            </div>
        </div>
    </section>
</aside>
<div class="modal fade in" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"
     data-backdrop="static" style="overflow:inherit;position: absolute;">
    <div class="modal-dialog" style="width: 800px !important;margin: 10px auto;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close close-product-model" data-dismiss="modal"><span
                        aria-hidden="true">&times;</span><span
                        class="sr-only">Close</span></button>
                <h4 class="modal-title" id="myModalLabel"><i class="fa fa-cubes"></i> Products</h4>
            </div>
            <form id="product-form" role="form">
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="box-body">
                            <div class="form-group">
                                <label for="product-name">Product Code</label>
                                <input type="hidden" id="product-id" name="product-id">
                                <input type="hidden" id="product-header-img" name="product-header-img">
                                <input type="text" class="form-control" id="product-name" name="product-name"
                                       placeholder="Enter Product Code" data-validation="required"
                                       data-validation-error-msg="Please enter Product Code.">
                            </div>
                            <div class="form-group">
                                <label for="product-details">Details</label>
                                <textarea class="form-control editor" id="product-details" name="product-details"
                                          placeholder="Enter Product Details" data-validation="required"
                                          data-validation-error-msg="Please enter Product Details."></textarea>
                            </div>
                            <div class="form-group">
                                <label for="product-details">Category</label>
                                <select class="form-control" id="product-category" name="product-category"
                                        data-validation="required"
                                        data-validation-error-msg="Please Select Product Category.">
                                    <option value="" default selected style="color:#999999;">Select your Category
                                    </option>
                                    <?php
                                    foreach ($categories as $category) {
                                        if ($category->getParent() == null) {
                                            echo "<option value='' style='color:#999999;'> ---" . $category->getName() . " --- </option>";
                                            foreach ($categories as $sub) {
                                                if ($sub->getParent() != null && $sub->getParent()->getId() == $category->getId()) {
                                                    echo "<option value='" . $sub->getId() . "'>" . $sub->getName() . "</option>";
                                                }
                                            }
                                        }
                                    }
                                    ?>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="product-details">Price
                                    <small>Per 100 pieces</small>
                                </label>
                                <input type="text" class="form-control" id="product-price" name="product-price"
                                       placeholder="Enter Product Price per 100 pieces" data-validation="number"
                                       data-validation-error-msg="Please enter Product Price." style="width:70%;">
                            </div>
                            <div class="form-group">
                                <label for="product-details">Discount
                                    <small>in percentage</small>
                                </label>
                                <input type="text" class="form-control" id="product-discount"
                                       name="product-discount" placeholder="Enter Product discount in Percentage."
                                       data-validation="number"
                                       data-validation-error-msg="Enter Product Discount." style="width:70%;">
                            </div>
                        </div>

                     </div>
                    <div class="col-md-6">
                        <div class="col-xs-12" style="height:150px;overflow-y: auto;padding: 0px 0px 0px 0px;">
                            <label>Upload Image</label>

                            <div id="mulitplefileuploader">Upload</div>
                            <div id="status"></div>
                        </div>
                        <div id="uploaded-img" class="col-xs-12"
                             style="height:280px;overflow-y:auto;padding:0px 0px 0px 0px;">
                        </div>
                        <div id="upload-img-template" class="col-md-4 product-gallery-image"
                             style="display: none;padding:0;">
                            <div class="col-md-12 product-gallery-image-header-banner">
                                <h6 align="center"
                                    style="margin-top: 1px; color: white; font-size: 11px ! important; font-weight: bold;">
                                    HEADER</h6>
                            </div>
                            <img class="product-gallery-image" style="width:100%;"
                                 data-bttrlazyloading-sm-width="117"
                                 data-bttrlazyloading-sm-height="80"
                                 data-bttrlazyloading-md-width="117"
                                 data-bttrlazyloading-md-height="80"
                                 data-bttrlazyloading-lg-width="117"
                                 data-bttrlazyloading-lg-height="80">
                            <div class="col-md-12 product-gallery-image-remove-banner">
                                <h6 align="center"
                                    style="margin-top: 1px; color: white; font-size: 11px ! important; font-weight: bold;">
                                    REMOVE</h6>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button id="submit-product" type="submit" class="btn btn-primary ladda-button" data-style="slide-right">
                    Save
                </button>
                <button type="button" class="btn btn-default close-product-model" data-dismiss="modal"> Close</button>
            </div>
            </form>
        </div>
    </div>
</div>
<?php include 'footer.php'; ?>
<script>
var imgUrl = "<?php echo img_url()?>";
var isRemoveImageCalled = false;
$(document).ready(function () {
    var settings = {
        url: "<?php echo base_url(). "scripts/upload.php"?>",
        dragDrop: true,
        fileName: "myfile",
        allowedTypes: "jpg,png,JPG,PNG,JPEG,jpeg",
        returnType: "json",
        showStatusAfterSuccess: false,
        onSuccess: function (files, data, xhr) {
            var div = $("#upload-img-template").clone();
            var str = data + "";
            str = str.replace('.', '-');
            $(div).attr("id", str);
            $(div).find(".product-gallery-image").attr("data-bttrlazyloading-sm-src", imgUrl + data);
            $(div).css("display", "block");
            $(div).find(".radio-button-header-img").val(data);
            $("#uploaded-img").append($(div));
            if ($("#uploaded-img").children().length == 1) {
                $(div).addClass("product-gallery-image-header");
                $(div).find(".product-gallery-image-header-banner").css("display", "block");
                $("#product-header-img").val(data);
            }
            $(div).find(".product-gallery-image").bttrlazyloading();
            $(div).find(".product-gallery-image").append("<input type='text' name='product-img[]' id='product-img[]' value='" + data + "'/>");

            //TODO: Remove Below line if Remove Image works.
            //$("#product-form").append("<input type='hidden' name='product-img[]' id='product-img[]' value='" + data + "'/>");
        },
        onError: function (u, data, t) {
            console.log(data);
            errorAlert("Something went wrong, Please contact administrator.");
        },
        showDelete: true,
        deleteCallback: function (data, pd) {
            for (var i = 0; i < data.length; i++) {
                var id = data[i];
                $.post("<?php echo base_url()."scripts/delete.php"?>", {op: "delete", name: data[i]}, function (resp, textStatus, jqXHR) {
                    var str = data + "";
                    str = str.replace('.', '-');
                    $("#" + str).remove();
                    $("input[id='product-img[]']").each(function () {
                        if (data == $(this).val()) {
                            $(this).remove();
                        }
                    });
                });
            }
            pd.statusbar.hide();
        }
    }
    var uploadObj = $("#mulitplefileuploader").uploadFile(settings);
});

$.validate({
    form: '#product-form',
    validateOnBlur: false,
    onError: function () {
        return false;
    },
    onSuccess: function ($form) {
        var headerImg = $("#product-header-img").val();
        if (headerImg != "" && headerImg != null) {
            var isEditProduct = $("#product-id").val() != "" ? true : false;
            var submitButton = Ladda.create(document.querySelector('#submit-product'));
            submitButton.start();
            var handler = $.post("addEditProduct", $("#product-form").serialize(), function (response) {
                if (!response.error) {
                    if (isEditProduct) {
                        var elementId = "product_" + response.data.id;
                        buildProductById(response.data, elementId);
                    } else {
                        displayProduct(response.data);
                    }
                    $form.resetForm();
                    clearProductModel();
                } else {
                    errorAlert(response.errorMessage);
                }
            })
                .error(function (error) {
                    console.log(error.responseText);
                    errorAlert("Please refresh page and try again, if Problem persist contact support team." + error.responseText);
                })
                .always(function () {
                    submitButton.stop();
                });
        } else {
            errorAlert("Please upload image for product. Product should have atlest 1 image.");
        }
        return false;
    }
});

function displayProduct(json) {
    var product = $("#display-product-template").clone().css("display", "block");
    var productGrid = $("#product-grid");
    var elementId = "product_" + json.id;
    $(product).attr("id", elementId);
    $(product).find(".product-delete").attr("product-id",json.id );
    $(product).hide().appendTo(productGrid).slideDown("fast");
    buildProductById(json, elementId);
}

function buildProductById(json, id) {
    var product = $("#" + id);
    var imagePath = "<?php img_url();?>";
    var grandTotalStock = 0;
    var grandTotalActualStock = 0;
    var actualStock = 0;
    var totalStock = 0;
    var locationId = $(product).find("select[name=p-location]").val();
    for (var i = 0; i < json.images.length; i++) {
        if (json.images[i].isCover) {
            imagePath += json.images[i].name;
        }
    }

    var isFirstItration = true;
    for (var i = 0; i < json.stock.length; i++) {
        if (isFirstItration) {
            if (locationId == -1) {
                isFirstItration = false;
                locationId = json.stock[i].location.id;
            } else {
                if (locationId == json.stock[i].location.id) {
                    isFirstItration = false;
                }
            }
            actualStock = json.stock[i].actualStock;
            totalStock = json.stock[i].totalStock;
        }
        grandTotalStock += json.stock[i].totalStock;
        grandTotalActualStock += json.stock[i].actualStock;
    }
    $(product).find("select[name=p-location]").val(locationId);
    $(product).find(".location-drop").attr("id", "product-drop_" + json.id);
    $(product).find(".product-stock-form-button").attr("id", "prod-button_" + json.id);
    $(product).find(".edit-product").attr("id", "product-edit_" + json.id);
    $(product).find(".display-product-name").text(json.name);
    $(product).find(".display-product-category").text(json.category.name);
    $(product).find(".p-image").attr("data-bttrlazyloading-sm-src", imagePath);
    $(product).find("input[name=p-id]").val(json.id);
    $(product).find(".product-total-stock").text(totalStock);
    $(product).find(".product-actual-stock").text(actualStock);
    $(product).find("input[name=p-price]").val(json.price);
    $(product).find("input[name=p-discount]").val(json.discount);
    $(product).find(".grand-total-actual-stock").text(grandTotalActualStock);
    $(product).find(".grand-total-stock").text(grandTotalStock);
    $(product).find(".p-image").bttrlazyloading({
        updatemanually: true
    });
    $(product).find(".p-image").trigger('bttrlazyloading.load');
}

$(document).ready(function () {
    $.get("getProduct",function (response) {
        if (!response.error) {
            for (var i = 0; i < response.data.length; i++) {
                displayProduct(response.data[i]);
            }
        } else {
            errorAlert(response.errorMessage);
        }
    }).always(function () {
            $(".product-grid-loader").hide();
        })
        .error(function (error) {
            errorAlert("Please refresh page and try again, if Problem persist contact support team." + error.responseText)
        });
});

$('body').on('submit', 'form.product-stock-form', function (event) {
    var btnId = "prod-button_" + $(this).find("input[name=p-id]").val();
    var locationId = $(this).find("select[name=p-location]").val();
    var discount = $(this).find("input[name=p-discount]").val();
    var price = $(this).find("input[name=p-price]").val();
    if (discount < 100) {
        if (price > 0) {
            var submitButton = Ladda.create(document.querySelector("#" + btnId));
            submitButton.start();
            $.post("updateStock", $(this).serialize(),function (product) {
                if (!product.error) {
                    var elementId = "product_" + product.data.id;
                    buildProductById(product.data, elementId);
                    $("#" + elementId).find("input[name=p-new-stock]").val(0);
                } else {
                    errorAlert(product.errorMessage);
                }
            }).always(function () {
                    submitButton.stop();
                });
        } else {
            errorAlert("Please enter Price.");
        }
    } else {
        errorAlert("Discount cannot be greated than 100%.");
    }
    event.preventDefault();
});

$('body').on('change', 'select.location-drop', function (event) {
    var id = $(this).val();
    var prodId = getElementId($(this).attr("id"));
    var product = $("#product_" + prodId);
    if (id > 0) {
        $(product).find(".overlay").show();
        $(product).find(".loading-img").show();
        $.get("getStock/" + id + "/" + prodId,function (response) {
            if (!response.error) {
                $(product).find(".product-total-stock").text(response.data.totalStock);
                $(product).find(".product-actual-stock").text(response.data.actualStock);
            } else {
                errorAlert(response.errorMessage);
            }
        }).always(function () {
                $(product).find(".overlay").hide();
                $(product).find(".loading-img").hide();
            });
    }
});

$(document).ready(function () {
    $("body").on("click", "div.product-gallery-image", function () {
        if(!isRemoveImageCalled){
            $(".product-gallery-image").removeClass("product-gallery-image-header");
            $(".product-gallery-image-header-banner").css("display", "none");
            $(this).addClass("product-gallery-image-header");
            $(this).find(".product-gallery-image-header-banner").css("display", "block");
            var imgName = $(this).attr("id");
            imgName = imgName.replace("-", ".");
            $("#product-header-img").val(imgName);
        }else{
            isRemoveImageCalled = false;
        }

    });


    $("body").on("click", ".product-gallery-image-remove-banner", function(){
        isRemoveImageCalled = true
        var headerImage =  $(this).parent(".product-gallery-image").attr("id");
        headerImage = headerImage.replace("-",".");
        if(headerImage == $("#product-header-img").val()){
            errorAlert("Cannot Delete Header Image !");
        }else{
            $(this).parent(".product-gallery-image").remove();
        }

    });

    $('body').on("click", "button.edit-product", function () {
        var btnId = $(this).attr("id");
        var productId = getElementId(btnId);
        var submitButton = Ladda.create(document.querySelector("#" + btnId));
        submitButton.start();
        $.get("getProduct/" + productId,function (response) {
            if (!response.error) {
                $("#product-id").val(response.data.id);
                $("#product-name").val(response.data.name);
                /*$("#product-details").val(response.data.details);*/
                $('#product-details').data("wysihtml5").editor.setValue(response.data.details);
                $("#product-category").val(response.data.category.id);
                $("#product-price").val(response.data.price);
                $("#product-discount").val(response.data.discount);
                for (var i = 0; i < response.data.images.length; i++) {
                    var data = response.data.images[i].name;

                    var div = $("#upload-img-template").clone();
                    var str = data + "";
                    str = str.replace('.', '-');
                    $(div).attr("id", str);
                    $(div).find(".product-gallery-image").attr("data-bttrlazyloading-sm-src", imgUrl + data);
                    $(div).css("display", "block");
                    $(div).find(".radio-button-header-img").val(data);
                    $("#uploaded-img").append($(div));

                    if (response.data.images[i].isCover) {
                        $(div).addClass("product-gallery-image-header");
                        $(div).find(".product-gallery-image-header-banner").css("display", "block");
                        $("#product-header-img").val(data);
                    }
                    $(div).find(".product-gallery-image").bttrlazyloading();
                    $(div).find(".product-gallery-image").append("<input type='text' name='product-img[]' id='product-img[]' value='" + data + "'/>");

                    //TODO: Remove Below line of Remove image works.
                    //$("#product-form").append("<input type='hidden' name='product-img[]' id='product-img[]' value='" + data + "'/>");


                }
                $('#myModal').modal('show');
            } else {
                errorAlert(response.errorMessage);
            }
        }).always(function () {
                submitButton.stop();
            });
    });

    $(".close-product-model").click(function () {
        clearProductModel();
    })

    $("#filter-search").click(function () {
        var pName = $("#filter-product-name").val();
        if (pName != null && pName != "") {
            var submitButton = Ladda.create(document.querySelector("#filter-search"));
            submitButton.start();
            var queryString = "product-name=" + pName;
            $.post('findProductByName', queryString, function (response) {
                if (!response.error) {
                    $("#product-grid").html("");
                    for (var i = 0; i < response.data.length; i++) {
                        displayProduct(response.data[i]);
                    }
                } else {
                    errorAlert(response.errorMessage);
                }
            })
                .always(function () {
                    submitButton.stop();
                });
        } else {
            errorAlert("Please Enter Product Name to Search.")
        }
    });

    $("#filter-category").change(function () {
        var id = $(this).val() == -1 ? "" : $(this).val();
        $(".product-grid-loader").show();
        $.get("findProductByCategory/" + id,function (response) {
            if (!response.error) {
                $("#product-grid").html("");
                for (var i = 0; i < response.data.length; i++) {
                    displayProduct(response.data[i]);
                }
            } else {
                errorAlert(response.errorMessage);
            }
        }).always(function () {
                $(".product-grid-loader").hide();
            });
    });

    $("body").on("mouseover",".product-gallery-image", function() {
            $(this).find(".product-gallery-image-remove-banner").show();
    });

    $("body").on("mouseout",".product-gallery-image", function(){
            $( this).find(".product-gallery-image-remove-banner").hide();
    });

    $("body").on("click",".product-delete",function(){
        var productId = $(this).attr("product-id");
        $.get("deleteproduct/"+ productId,function(response){
            if(!response.error){
                $("#product_"+ productId).remove();
            }else{
                errorAlert(response.errorMessage);
            }
        });
    });
});


function clearProductModel() {
    $("#product-id").val("");
    $("#product-name").val("");
    $("#product-details").val("");
    $("#product-category").val("");
    $("#product-price").val("");
    $("#product-discount").val("");
    $("#uploaded-img").html("");
    $("input[id='product-img[]']").each(function () {
        $(this).remove();
    });
}
</script>
